<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="业务员" prop="salesperson">
        <el-input
          v-model="queryParams.salesperson"
          placeholder="请输入业务员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="mb-10px">
      <el-button
        type="primary"
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['report:order-cost-marketing:export']"
      >
        数据导出
      </el-button>
      <el-button
        type="primary"
        @click="batchUpdate"
        v-hasPermi="['report:order-cost-marketing:update']"
      >
        批量编辑
      </el-button>
    </div>
    <el-table 
      v-loading="loading" 
      :data="list"
      row-key="id"
      :height="tableHeight"
      @selection-change="handleSelectionChange"
      ref="multipleTableRef"
    >
      <el-table-column align="center" type="selection" fixed="left" />
      <el-table-column label="序号" align="center" type="index" width="60" fixed="left" />
      <el-table-column 
        v-for="item, index in listTableTitleList"
        :key="index"
        :label="item.label" 
        :headerAlign="item.headerAlign"
        :align="item.align" 
        :min-width="item.width"
        :prop="item.field"
      >
        <template #default="scope" >
          <template v-if="item.children">
            <el-table-column 
              v-for="child, childIndex in item.children"
              :key="childIndex"
              :label="child.label" 
              :align="child.align" 
              :headerAlign="child.headerAlign"
              :prop="child.field"
              :min-width="child.width"
            >
              <template #default="scope">
                <dict-tag v-if="child['dictType']" :type="child['dictType']" :value="scope.row[child.field]" />
                <template v-else>
                  <div v-if="['firstBid', 'transactionPrice'].includes(child.field)">{{ scope.row[child.field].toFixed(4) }}</div>
                  <div v-else>{{ scope.row[child.field] }}</div>
                </template>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
            <template v-else>
              <div v-if="item.isTime">{{ formatDate(scope.row[item.field]) }}</div>
              <div v-else>{{ scope.row[item.field] }}</div>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" fixed="right" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-if="scope.row.dictMarkStatus === 10"
            v-hasPermi="['report:order-cost-marketing:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('view', scope.row.id)"
            v-hasPermi="['report:order-cost-marketing:view']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
</template>

<script setup lang="ts" name="OrderCostMarketing">
import download from '@/utils/download'
import * as OrderCostMarketingApi from '@/api/reportQuery/orderReport/orderCostMarketing'
import { listTableTitleList } from './tableTitle-data'
import { formatDate } from '@/utils/formatTime'

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  customerName: null,
  salesperson: null,
  createTime: [],
  productNumber: null,
  productName: null,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const tableHeight = ref(0)

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderCostMarketingApi.getOrderCostMarketingPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const { push } = useRouter() // 路由
const openForm = (type: string, id) => {
  push({
    path: '/reportQuery/reportQuery/orderReport/orderCostMarketingDetail',
    query: {
      id,
      type
    }
  })
}

// 批量编辑
const batchUpdate = () => {
  if (!multipleSelection.value.length) {
    message.notifyError('请至少选择一条数据')
    return
  }
  let id = multipleSelection.value.map(v => v['id']).join(',')
  openForm('update', id)
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 下载
const multipleTableRef = ref()
const downloadFun = async () => {
  const val = exportRef.value.params
  const params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = multipleSelection.value.map((item) => {
      return item['id']
    })
  }
  const data = await OrderCostMarketingApi.exportOrderCostMarketing(params)
  download.excel(data, val.name)
  multipleTableRef.value!.clearSelection()
  multipleSelection.value = []
}

/** 初始化 **/
onMounted(() => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 112
  getList()
})
</script>
